package com.example.newsapp.activity;

import static com.example.newsapp.constant.NetConstant.BASE_URL;

import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.newsapp.R;
import com.example.newsapp.model.Result;
import com.example.newsapp.model.User;
import com.example.newsapp.utils.HttpUtil;
import com.example.newsapp.utils.UserSessionUtil;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;

public class ProfileActivity extends AppCompatActivity {
    private TextView usernameTextView;
    private EditText nicknameEditText;
    private EditText ageEditText;
    private EditText emailEditText;
    private RadioButton maleRadioButton;
    private RadioButton femaleRadioButton;
    private Button saveButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile);

        initViews();

        // 设置返回按钮
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setTitle("个人信息");
        }

        // 加载用户信息
        loadUserInfo();

        // 设置保存按钮点击事件
        saveButton.setOnClickListener(v -> saveUserInfo());
    }

    private void initViews() {
        findViewById(R.id.btnBack).setOnClickListener(v -> finish());

        usernameTextView = findViewById(R.id.usernameTextView);
        usernameTextView.setOnClickListener(v -> {
            Toast.makeText(this, "用户名不可修改", Toast.LENGTH_SHORT).show();
        });
        nicknameEditText = findViewById(R.id.nicknameEditText);
        ageEditText = findViewById(R.id.ageEditText);
        emailEditText = findViewById(R.id.emailEditText);
        maleRadioButton = findViewById(R.id.maleRadioButton);
        femaleRadioButton = findViewById(R.id.femaleRadioButton);
        saveButton = findViewById(R.id.saveButton);
    }

    private void loadUserInfo() {
        int userId = UserSessionUtil.getUserId(this);
        if (userId == -1) {
            Toast.makeText(this, "用户未登录，加载失败", Toast.LENGTH_SHORT).show();
            return;
        }
        requestUserInfo();
    }

    private void saveUserInfo() {
        int userId = UserSessionUtil.getUserId(this);
        if (userId == -1) {
            showToast("用户未登录，保存失败");
            return;
        }

        User user = tryBuildUserFromInput(userId);
        if (user == null) return;

        requestUpdateUser(user);
    }

    private void requestUserInfo() {
        String requestUrl = BASE_URL + "/users";

        Type resultType = new TypeToken<Result<User>>() {
        }.getType();

        HttpUtil.request(ProfileActivity.this,requestUrl, "GET", null, resultType, new HttpUtil.Callback<Result<User>>() {
            @Override
            public void onSuccess(Result<User> result) {
                handleUserInfoResponse(result);
            }

            @Override
            public void onFailure(Exception e) {
                showToast("查询出错");
            }
        });
    }

    private void requestUpdateUser(User user) {
        String requestUrl = BASE_URL + "/users";
        Type resultType = new TypeToken<Result<String>>() {
        }.getType();

        HttpUtil.request(ProfileActivity.this,requestUrl, "PUT", user, resultType, new HttpUtil.Callback<Result<String>>() {
            @Override
            public void onSuccess(Result<String> result) {
                handleUpdateResponse(result);
            }

            @Override
            public void onFailure(Exception e) {
                showToast("网络异常：" + e.getMessage());
            }
        });
    }

    private void handleUserInfoResponse(Result<User> result) {
        if (result == null) {
            showToast("服务器响应异常");
            return;
        }

        if (result.getCode() == 1 && result.getData() != null) {
            updateUIWithUser(result.getData());
        } else {
            String errorMsg = result.getMsg();
            if (errorMsg == null || errorMsg.isEmpty()) errorMsg = "未知错误";
            showToast("查询失败：" + errorMsg);
        }
    }

    private void handleUpdateResponse(Result<String> result) {
        if (result == null) {
            showToast("服务器响应异常");
            return;
        }
        if (result.getCode() == 1 && result.getData() != null) {
            showToast(result.getData());
            finish();
        } else {
            String errorMsg = result.getMsg();
            if (errorMsg == null || errorMsg.isEmpty()) errorMsg = "未知错误";
            showToast("保存失败：" + errorMsg);
        }
    }

    private void updateUIWithUser(User data) {
        usernameTextView.setText(data.getusername());
        nicknameEditText.setText(data.getNickname());
        Integer age = data.getAge();
        ageEditText.setText(age != null ? String.valueOf(age) : "");
        emailEditText.setText(data.getEmail());

        if ("男".equals(data.getGender())) {
            maleRadioButton.setChecked(true);
        } else if ("女".equals(data.getGender())) {
            femaleRadioButton.setChecked(true);
        }
    }

    private User tryBuildUserFromInput(int userId) {
        String ageStr = ageEditText.getText().toString();
        try {
            Integer age = null;
            if(!ageStr.isEmpty()){
                age = Integer.parseInt(ageStr);
            }
            return new User(
                    userId,
                    usernameTextView.getText().toString(),
                    nicknameEditText.getText().toString(),
                    maleRadioButton.isChecked() ? "男" : (femaleRadioButton.isChecked() ? "女" : ""),
                    age,
                    emailEditText.getText().toString()
            );
        } catch (NumberFormatException e) {
            showToast("年龄必须是数字");
            return null;
        }
    }

    private void showToast(String msg) {
        Toast.makeText(ProfileActivity.this, msg, Toast.LENGTH_SHORT).show();
    }

}